package com.redsoft.spirit.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.redsoft.spirit.entity.AccessToken;
import com.redsoft.spirit.entity.Account;
import com.redsoft.spirit.entity.Authorization;
import com.redsoft.spirit.entity.Department;
import com.redsoft.spirit.entity.JsonResult;
import com.redsoft.spirit.entity.JwtProperty;
import com.redsoft.spirit.entity.ResultStatusCode;
import com.redsoft.spirit.service.AccountService;
import com.redsoft.spirit.service.AuthorizationService;
import com.redsoft.spirit.service.DeptService;
import com.redsoft.spirit.service.IAccountService;
import com.redsoft.spirit.util.jwt.JwtHelper;

@RestController
public class AccountController {

	@Autowired
	private AccountService accountService;

	@Resource
	private IAccountService userService;

	@Resource
	private DeptService deptService;

	@Autowired
	private AuthorizationService authorizationService;

	private Gson gson = new Gson();

	@Autowired
	private JwtProperty jwtProperty;

	// @ApiOperation(value="输出自定义的Properties配置解析类内容")
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public String getJwtInfo() {
		JsonResult result = new JsonResult(jwtProperty);
		return gson.toJson(result.success());
	}

	/**
	 * 登录
	 * 
	 * <pre>
	 * 登录
	 * </pre>
	 * 
	 * @author 李晓东
	 * @param accountName
	 * @param accountPwd
	 * @param clientId
	 * @param mobileType
	 *            手机型号
	 * @param deviceToken
	 *            华为设备token（推送用到）
	 * @param logonMode
	 *            0APP登录，1后台登录 默认为0，前台APP登录用
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	// @ApiOperation(value = "使用JWT进行token验证，传入登录参数")
	@RequestMapping(value = "/oauth/token", method = RequestMethod.POST)
	public String getAccessToken(String accountName, String accountPwd, String clientId, String mobileType,
			String deviceToken,
			@RequestParam(value = "logonMode", required = false, defaultValue = "0") int logonMode) {
		JsonResult result = new JsonResult();

		try {
			if (clientId == null || (clientId.compareTo(jwtProperty.getClientId()) != 0)) {

				result.setStatus(ResultStatusCode.INVALID_CLIENTID.getErrorCode());
				result.setMsg(ResultStatusCode.INVALID_CLIENTID.getErrorMsg());

				return gson.toJson(result);
			}

			Account user = null;
			try {
				user = userService.login(accountName, accountPwd, logonMode);
				accountService.updateLogin(accountName, mobileType, deviceToken);
			} catch (Exception e) {

				return new JsonResult(null, e.getMessage()).failure().toString();
			}

			Department dept = deptService.getDeptByUserId(user.getId());

			// 拼装accessToken
			String accessToken = JwtHelper.createJWT(accountName, user.getId(), "userRole", jwtProperty.getClientId(),
					jwtProperty.getName(), jwtProperty.getExpiresSecond() * 1000, jwtProperty.getBase64Secret());

			// 返回accessToken
			AccessToken accessTokenEntity = new AccessToken();
			accessTokenEntity.setAccessToken("bearer " + accessToken);
			// accessTokenEntity.setExpiresIn(jwtProperty.getExpiresSecond());
			// accessTokenEntity.setTokenType("bearer");
			// accessTokenEntity.setAccount(user);
			// resultMsg = new ResultMsg<Object>(true,
			// ResultStatusCode.OK.getErrorCode(),
			// ResultStatusCode.OK.getErrorMsg(), accessTokenEntity);

			Map map = new HashMap<>();
			map.put("accessToken", "bearer " + accessToken);
			map.put("userId", user.getId());
			map.put("realName", user.getRealName());
			map.put("phoneNo", user.getPhoneNo());
			map.put("accountName", user.getAccountName());
			map.put("avatar", user.getAvatar());
			map.put("deptId", dept.getId());
			map.put("deptName", dept.getName());

			// 如果是后台管理登录的话，则继续查询一下这个人的所有的权限，所有的操作授权数据
			if (logonMode == 1) {
				List<Authorization> lst = authorizationService.getAuthorizationsByUserId(user.getId());
				List perms = new ArrayList<>();

				for (Authorization object : lst) {
					perms.add(object.getPageInnerName() + ":" + object.getElementInnerName());
				}
				map.put("perms", perms);
			}

			result.setStatus(ResultStatusCode.OK.getErrorCode());
			result.setMsg(ResultStatusCode.OK.getErrorMsg());
			result.setData(map);

			return gson.toJson(result);
		} catch (Exception ex) {
			// resultMsg = new ResultMsg<Object>(false,
			// ResultStatusCode.SYSTEM_ERR.getErrorCode(),
			// ResultStatusCode.SYSTEM_ERR.getErrorMsg(), null);
			result.setStatus(ResultStatusCode.SYSTEM_ERR.getErrorCode());
			result.setMsg(ResultStatusCode.SYSTEM_ERR.getErrorMsg());

			return gson.toJson(result);
		}
	}

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public String userList(int offset, int limit, String searchKey, String deptId) {

		JsonResult result = new JsonResult();

		try {
			HashMap map = accountService.getJsonData(offset, limit, searchKey, deptId);
			result.setData(map);

			return result.success().toString("yyyy-MM-dd HH:mm:ss");
		} catch (Exception e) {
			result.setMsg(e.getMessage());
			return gson.toJson(result.failure());
		}
	}

	/**
	 * 
	 * 添加人员.
	 * 
	 * <pre>
	 * 	添加人员，并把部门关系添加上
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param dept
	 * @return
	 */
	@RequestMapping(value = "/users", method = RequestMethod.POST)
	public String addUser(@RequestBody Account user, String deptId) {

		try {
			accountService.saveOrUpdate(user, deptId);

			JsonResult result = new JsonResult();

			return result.success().toString();
		} catch (Exception e) {
			JsonResult result = new JsonResult(null, e.getMessage());

			return result.failure().toString();
		}
	}

	/**
	 * 
	 * 添加部门.
	 * 
	 * <pre>
	 * 	添加部门，页面传过来部门的实体类信息
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param dept
	 * @return
	 */
	@RequestMapping(value = "/users/changeDeptEmp", method = RequestMethod.POST)
	public String changeDeptEmp(String userId, String deptId) {

		try {
			accountService.changeDeptEmp(userId, deptId);

			JsonResult result = new JsonResult();

			return result.success().toString();
		} catch (Exception e) {
			JsonResult result = new JsonResult(null, e.getMessage());

			return result.failure().toString();
		}
	}

	@RequestMapping(value = "/users/{userId}", method = RequestMethod.PUT)
	public String approve(@PathVariable String userId, String isActive) {

		try {
			accountService.update(userId, isActive);

			JsonResult result = new JsonResult();

			return result.success().toString();
		} catch (Exception e) {
			JsonResult result = new JsonResult(null, e.getMessage());

			return result.failure().toString();
		}
	}
	

	/**
	 * 
	 * 修改密码
	 * <pre>
	 * 修改密码
	 * </pre>
	 * 
	 * @author lixiaodong
	 * @param userId
	 * @param password
	 * @param newPasswd
	 * @return
	 */
	@RequestMapping(value = "/users/{userId}/passwd", method = RequestMethod.POST)
	public String updatePasswd(@PathVariable String userId, String password, String newPasswd) {

		try {
			Account account = accountService.getById(userId);
			if (account == null) {
				return new JsonResult(null, "帐号不存在！").failure().toString();
			}
			String secretPwd = new Md5Hash(password, "meiyoumima").toString();
			if (!secretPwd.equals(account.getAccountPwd())) {
				return new JsonResult(null, "输入原密码错误！").failure().toString();
			}
			accountService.updatePassword(account, newPasswd);
			
			return new JsonResult().success().toString();
		} catch (Exception e) {

			return  new JsonResult(null, e.getMessage()).failure().toString();
		}
	}
	
	/**
	 * 
	 * 获取帐号详情
	 * <pre>
	 * 获取帐号详情
	 * </pre>
	 * 
	 * @author lixiaodong
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/users/{userId}", method = RequestMethod.GET)
	public String getUser(@PathVariable String userId) {
		
		try {
			Account account = accountService.getById(userId);
			if (account == null) {
				return new JsonResult(null, "帐号不存在！").failure().toString();
			}

			return new JsonResult(account).success().toString();
		} catch (Exception e) {

			return new JsonResult(null, e.getMessage()).failure().toString();
		}
	}

	/**
	 * 删除人员.
	 * 
	 * <pre>
	 * 删除人员并从部门关联表中删除掉关系
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param dept
	 * @return
	 */
	@RequestMapping(value = "/users", method = RequestMethod.DELETE)
	public String deleteUsers(String userIds) {
		try {
			String[] users = userIds.split(",");
			List<String> list = java.util.Arrays.asList(users);
			accountService.deleteUsers(list);
			JsonResult result = new JsonResult();
			return result.success().toString();
		} catch (Exception e) {
			JsonResult result = new JsonResult(null, e.getMessage());
			return result.failure().toString();
		}
	}
}